#pragma once
#include <iostream>
#include <string>
#include <cstring>
#include <unordered_map>
#include <functional>
#include <memory>
#include "TcpServer.hpp"
#include "HttpProtocol.hpp"

using http_handler_t = std::function<void(HttpRequest &, HttpResponse &)>;
using namespace TcpSeverModule;

class HttpSever
{
public:
    HttpSever(int port) : _tcps(std::make_unique<TcpSever>(port))
    {
    }
    void Resgiter(std::string funcname, http_handler_t func)
    {
        _route[funcname] = func;
    }
    bool SafeCheck(std::string &method)
    {
        for(auto &it : _route)
        {
            if(it.first == method)
            {
                return true;
            }
        }
        return false;
    }
    void Start()
    {
        _tcps->TcpInit([this](sockptr sockfd, InetAddr client)
                       { return this->HandlerHttpRequest(sockfd, client); });
        _tcps->Loop();
    }
    bool HandlerHttpRequest(sockptr sockfd, InetAddr client)
    {
        LOG(LogLevel::DEBUG) << "accept a new client" << client.Addr();
        std::string request;
        sockfd->Rec(&request);
        HttpRequest req;
        req.Deserialize(request);


        HttpResponse resp;
        if(req.IsArgs())
        {
            LOG(LogLevel::DEBUG) << "------客户端在请求:  IsArgs" << req.Path();
            std::string method = req.Path();
            //安全检查
            if(SafeCheck(method))
            {
                _route[method](req, resp);
                LOG(LogLevel::DEBUG) << "------客户端在执行: " << req.Path();
            }
            else
            resp.Build(req);  
        }
        else
        {
          resp.Build(req);  
        }
        

        std::string resp_str;
        resp.Serialize(&resp_str);
        sockfd->Send(resp_str);
        return true;
    }

private:
    std::unique_ptr<TcpSever> _tcps;
    std::unordered_map<std::string, http_handler_t> _route; // 功能路由
};
